package main

import (
	"fmt"
	"reflect"
)

func main() {
	stu := Student{
		Name:  "zw",
		Age:   12,
		Score: 90.9,
	}
	// 修改值传引用
	reflectModify01(&stu)
	fmt.Println(stu)
}

// 通过反射
func reflectModify01(a interface{}) {
	typ := reflect.TypeOf(a)
	kind := typ.Kind()
	if kind != reflect.Ptr {
		return
	}
	value := reflect.ValueOf(a)
	val := value.Elem()
	// 字段
	num := val.NumField()
	fmt.Printf("struce has %d fields \n", num)
	for i := 0; i < num; i++ {
		// 获取的值不能运算，需要转换
		fmt.Printf("Field %d,值为=%v\n", i, val.Field(i))
		// 获取标签 tag
		tag := typ.Elem().Field(i).Tag.Get("json")
		if tag != "" {
			fmt.Printf("Field %d,tag为=%v\n", i, tag)
		}
	}
	val.FieldByName("Name").SetString("update")

	// 方法
	methodNum := val.NumMethod()
	fmt.Printf("struce has %d methods \n", methodNum)
	val.MethodByName("Test").Call(nil)
	var param []reflect.Value
	param = append(param, reflect.ValueOf(10))
	param = append(param, reflect.ValueOf(20))
	res := val.MethodByName("GetSum").Call(param)
	fmt.Println("res = ", res[0])

}

type Student struct {
	Name  string `json:"name"`
	Age   int
	Score float64
}

func (stu Student) Test() {
	fmt.Println("==start==")
	fmt.Println(stu)
	fmt.Println("==end==")
}

func (stu Student) GetSum(n1 int, n2 int) int {
	return n1 + n2
}

func (stu *Student) GetSum2(n1 int, n2 int) int {
	return n1 + n2
}
